<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { NButton, NSpace, NTag, NProgress, NDrawer, NDescriptions, NDescriptionsItem, NCard, NStatistic, NGrid, NGridItem } from 'naive-ui';
import { fetchCollectionTaskList, fetchTaskDetail, stopTask, retryTask, fetchTaskStatistics, fetchTaskTrend } from '@/service/api/dataplatform/file-collection';
import type { CollectionTask } from '@/typings/api/dataplatform.api';

const loading = ref(false);
const taskList = ref<CollectionTask[]>([]);
const total = ref(0);
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  ruleId: undefined as number | undefined,
  status: undefined as string | undefined,
  taskCode: undefined as string | undefined
});

// 任务详情抽屉
const detailDrawerVisible = ref(false);
const currentTask = ref<CollectionTask | null>(null);

// 统计数据
const statistics = ref({
  totalTasks: 0,
  successTasks: 0,
  failedTasks: 0,
  runningTasks: 0,
  successRate: '0.00'
});

// 趋势数据
const trendData = ref<any[]>([]);

// 状态映射
const statusMap: Record<string, { label: string; type: 'success' | 'error' | 'warning' | 'info' }> = {
  PENDING: { label: '待执行', type: 'info' },
  RUNNING: { label: '执行中', type: 'warning' },
  SUCCESS: { label: '成功', type: 'success' },
  FAILED: { label: '失败', type: 'error' }
};

// 加载任务列表
const loadTaskList = async () => {
  loading.value = true;
  try {
    const { data } = await fetchCollectionTaskList(queryParams);
    taskList.value = data.rows;
    total.value = data.total;
  } finally {
    loading.value = false;
  }
};

// 加载统计数据
const loadStatistics = async () => {
  const { data } = await fetchTaskStatistics(queryParams.ruleId);
  statistics.value = data;
};

// 加载趋势数据
const loadTrend = async () => {
  const { data } = await fetchTaskTrend(queryParams.ruleId, 7);
  trendData.value = data;
};

// 查看详情
const handleViewDetail = async (row: CollectionTask) => {
  const { data } = await fetchTaskDetail(row.id);
  currentTask.value = data;
  detailDrawerVisible.value = true;
};

// 停止任务
const handleStopTask = async (row: CollectionTask) => {
  await stopTask(row.id);
  window.$message?.success('任务已停止');
  await loadTaskList();
};

// 重跑任务
const handleRetryTask = async (row: CollectionTask) => {
  await retryTask(row.id);
  window.$message?.success('任务已重新触发');
  await loadTaskList();
};

// 搜索
const handleSearch = () => {
  queryParams.pageNum = 1;
  loadTaskList();
};

// 重置
const handleReset = () => {
  queryParams.ruleId = undefined;
  queryParams.status = undefined;
  queryParams.taskCode = undefined;
  handleSearch();
};

// 分页变化
const handlePageChange = (page: number) => {
  queryParams.pageNum = page;
  loadTaskList();
};

// 计算进度
const calculateProgress = (task: CollectionTask) => {
  if (task.totalRecords === 0) return 0;
  return Math.round(((task.successRecords || 0) / task.totalRecords) * 100);
};

onMounted(() => {
  loadTaskList();
  loadStatistics();
  loadTrend();
});
</script>

<template>
  <div class="file-collection-task-page">
    <!-- 统计卡片 -->
    <NGrid :cols="4" :x-gap="16" class="mb-4">
      <NGridItem>
        <NCard>
          <NStatistic label="总任务数" :value="statistics.totalTasks" />
        </NCard>
      </NGridItem>
      <NGridItem>
        <NCard>
          <NStatistic label="成功任务" :value="statistics.successTasks" />
        </NCard>
      </NGridItem>
      <NGridItem>
        <NCard>
          <NStatistic label="失败任务" :value="statistics.failedTasks" />
        </NCard>
      </NGridItem>
      <NGridItem>
        <NCard>
          <NStatistic label="成功率" :value="statistics.successRate" suffix="%" />
        </NCard>
      </NGridItem>
    </NGrid>

    <!-- 搜索表单 -->
    <NCard class="mb-4">
      <NSpace>
        <NInput
          v-model:value="queryParams.taskCode"
          placeholder="任务编码"
          clearable
          style="width: 200px"
        />
        <NSelect
          v-model:value="queryParams.status"
          placeholder="任务状态"
          clearable
          style="width: 150px"
          :options="[
            { label: '待执行', value: 'PENDING' },
            { label: '执行中', value: 'RUNNING' },
            { label: '成功', value: 'SUCCESS' },
            { label: '失败', value: 'FAILED' }
          ]"
        />
        <NButton type="primary" @click="handleSearch">
          <template #icon>
            <icon-ic-round-search />
          </template>
          搜索
        </NButton>
        <NButton @click="handleReset">
          <template #icon>
            <icon-ic-round-refresh />
          </template>
          重置
        </NButton>
      </NSpace>
    </NCard>

    <!-- 任务列表 -->
    <NCard title="采集任务列表">
      <NDataTable
        :loading="loading"
        :columns="[
          { title: '任务编码', key: 'taskCode', width: 200 },
          { title: '规则名称', key: 'ruleName', width: 150 },
          {
            title: '状态',
            key: 'status',
            width: 100,
            render: (row: CollectionTask) => {
              const status = statusMap[row.status];
              return h(NTag, { type: status.type }, { default: () => status.label });
            }
          },
          {
            title: '进度',
            key: 'progress',
            width: 150,
            render: (row: CollectionTask) => {
              const progress = calculateProgress(row);
              return h(NProgress, {
                type: 'line',
                percentage: progress,
                status: row.status === 'SUCCESS' ? 'success' : row.status === 'FAILED' ? 'error' : 'default'
              });
            }
          },
          { title: '文件数', key: 'fileCount', width: 80 },
          { title: '总记录数', key: 'totalRecords', width: 100 },
          { title: '成功记录数', key: 'successRecords', width: 120 },
          { title: '失败记录数', key: 'failedRecords', width: 120 },
          { title: '开始时间', key: 'startTime', width: 180 },
          { title: '结束时间', key: 'endTime', width: 180 },
          {
            title: '操作',
            key: 'actions',
            width: 200,
            fixed: 'right',
            render: (row: CollectionTask) => {
              return h(NSpace, {}, {
                default: () => [
                  h(NButton, {
                    size: 'small',
                    onClick: () => handleViewDetail(row)
                  }, { default: () => '详情' }),
                  row.status === 'RUNNING' && h(NButton, {
                    size: 'small',
                    type: 'warning',
                    onClick: () => handleStopTask(row)
                  }, { default: () => '停止' }),
                  (row.status === 'FAILED' || row.status === 'SUCCESS') && h(NButton, {
                    size: 'small',
                    type: 'primary',
                    onClick: () => handleRetryTask(row)
                  }, { default: () => '重跑' })
                ]
              });
            }
          }
        ]"
        :data="taskList"
        :pagination="{
          page: queryParams.pageNum,
          pageSize: queryParams.pageSize,
          itemCount: total,
          onUpdatePage: handlePageChange
        }"
        :scroll-x="1600"
      />
    </NCard>

    <!-- 任务详情抽屉 -->
    <NDrawer v-model:show="detailDrawerVisible" :width="600" title="任务详情">
      <NCard v-if="currentTask">
        <NDescriptions :column="1" bordered>
          <NDescriptionsItem label="任务编码">
            {{ currentTask.taskCode }}
          </NDescriptionsItem>
          <NDescriptionsItem label="规则名称">
            {{ currentTask.ruleName }}
          </NDescriptionsItem>
          <NDescriptionsItem label="状态">
            <NTag :type="statusMap[currentTask.status].type">
              {{ statusMap[currentTask.status].label }}
            </NTag>
          </NDescriptionsItem>
          <NDescriptionsItem label="文件数量">
            {{ currentTask.fileCount }}
          </NDescriptionsItem>
          <NDescriptionsItem label="总记录数">
            {{ currentTask.totalRecords }}
          </NDescriptionsItem>
          <NDescriptionsItem label="成功记录数">
            {{ currentTask.successRecords }}
          </NDescriptionsItem>
          <NDescriptionsItem label="失败记录数">
            {{ currentTask.failedRecords }}
          </NDescriptionsItem>
          <NDescriptionsItem label="开始时间">
            {{ currentTask.startTime }}
          </NDescriptionsItem>
          <NDescriptionsItem label="结束时间">
            {{ currentTask.endTime || '-' }}
          </NDescriptionsItem>
          <NDescriptionsItem v-if="currentTask.errorMessage" label="错误信息">
            <span class="text-red-500">{{ currentTask.errorMessage }}</span>
          </NDescriptionsItem>
        </NDescriptions>
      </NCard>
    </NDrawer>
  </div>
</template>

<style scoped>
.file-collection-task-page {
  padding: 16px;
}
</style>
